import { isEmpty } from 'lodash-es'
let cache = {}
let handle: Promise<void> | null = null

const subject = (value: any): Promise<void> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.info('getValue')
      console.info(value)
      resolve()
    }, 100)
  })
}

const publish = async(params) => {
  if (isEmpty(cache)) {
    Object.assign(cache, params)
    if (handle) {
      await handle
      exec()
    } else {
      exec()
    }
  } else {
    Object.assign(cache, params)
  }
}

const exec = async() => {
  handle = subject(cache)
  cache = {}
  await handle
  handle = null
}

publish({ a: 1 })
publish({ a: 2 })
publish({ b: 2 })
publish({ a: 2 })
